#include "global.h"
#include "term_caps.c"
#include <termios.h>

static struct {
    bool is_raw;
    struct termios mode;
} g_term = {0};

static int enter_raw_mode()
{
    struct termios mode = {0};

    if (tcgetattr(global.tty_fd, &mode) != 0) {
        return TB_ERR;
    }

    memcpy(&g_term.mode, &mode, sizeof(mode));

    cfmakeraw(&mode);
    mode.c_cc[VMIN] = 1;
    mode.c_cc[VTIME] = 0;

    if (tcsetattr(global.tty_fd, TCSAFLUSH, &mode) != 0) {
        return TB_ERR;
    }

    g_term.is_raw = true;

    return TB_OK;
}

static int exit_raw_mode()
{
    if (g_term.is_raw) {
        if (tcsetattr(global.tty_fd, TCSAFLUSH, &g_term.mode) != 0) {
            return TB_ERR;
        }
    }
    return TB_OK;
}


static int load_caps()
{
    const char *term = getenv("TERM");
    if (term == NULL)
        return TB_ERR;

    for (int i = 0; builtin_terms[i].name != NULL; i++) {
        if (strcmp(term, builtin_terms[i].name) == 0) { // match term
            for (int j = 0; j < TB_CAP__COUNT; j++) {
                global.caps[j] = builtin_terms[i].caps[j];
            }
            return TB_OK;
        }
    }

    return TB_ERR;
}

int term_init()
{
    memset(&g_term, 0, sizeof(g_term));
    enter_raw_mode();
    load_caps();
}

int term_deinit()
{
    exit_raw_mode();
    memset(&g_term, 0, sizeof(g_term));
}
